package com.artup.controller;

import java.util.Iterator;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.pojo.Material;
import com.artup.service.MaterialService;
import com.artup.to.MaterialTo;
import com.artup.util.CommonUtils;
import com.artup.util.file.FileUploadUtil;
import com.artup.util.file.FolderUtils;
import com.artup.util.file.PropertiesUtils;
import com.artup.util.os.OperationSystemInfo;
import com.artup.util.shell.ChmodShell;

/**
 * 素材 
 * @author hapday
 * @date 2017年7月21日 @Time 上午10:56:38
 */
@RestController
@RequestMapping( value = { "admin/material" } )
public class MaterialController {
	private static final Logger LOGGER = LoggerFactory.getLogger(MaterialController.class);
	
	@Autowired
	private MaterialService materialService;
	
	/**
	 * 查询【素材列表】
	 * @param userId
	 * @param width
	 * @param height
	 * @param currentPageIndex
	 * @param pageSize
	 * @return
	 */
	@RequestMapping( value = { "queryMaterialList/{passportId}" } )
	public ResponseResult queryMaterialList(@PathVariable int passportId, Integer width, Integer height, Integer currentPageIndex, Integer pageSize) {
		LOGGER.info("passportId = {}, width = {}, height = {}, currentPageIndex = {}, pageSize = {}", passportId, width, height, currentPageIndex, pageSize);
		
		ResponseResult responseResult = this.materialService.queryMaterialListByPassportId(passportId, width, height, currentPageIndex, pageSize);
		
		return responseResult;
	}

	/**
	 * 查询【素材列表】
	 * @param material 【素材】
	 * @return 【素材列表】
	 */
	@RequestMapping( value = { "queryMaterials" } )
	public ResponseResult queryMaterials(Material material) {
		LOGGER.info("material = {}", JSONObject.toJSONString(material));
		
		ResponseResult responseResult = this.materialService.queryMaterialList(material);
		
		return responseResult;
	}
	
	/**
	 * 查询【素材】
	 * @param id 【ID】
	 * @param width 宽
	 * @param height 高
	 * @return
	 */
	/*@RequestMapping( value = { "queryMaterial/{id}" } )
	public ResponseResult queryMaterial(@PathVariable String id, Integer width, Integer height) {
		LOGGER.info("id = {}, width = {}, height = {}", id, width, height);
		
		ResponseResult responseResult = this.materialService.queryMaterialById(id, width, height);
		
		return responseResult;
	}*/

	@RequestMapping( value = { "queryMaterial/{id}" } )
	public ResponseResult queryMaterial(@PathVariable String id) {
		LOGGER.info("id = {}", id);
		
		ResponseResult responseResult = this.materialService.queryMaterialById(id);
		
		return responseResult;
	}
	
	/**
	 * 上传素材
	 * @param id
	 * @param multipartRequest
	 * @return
	 */
	@RequestMapping( value = { "uploadMerial/{passportId}" } )
	public @ResponseBody ResponseResult uploadMerial(@PathVariable Integer passportId, String clientCode, MultipartHttpServletRequest multipartRequest ) {
		LOGGER.info("passportId = {}, clientCode = {}", passportId, clientCode);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(null == passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("【通行证ID】不可为空！");
			
			return responseResult;
		} else if(0 >= passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_NOT_POSITIVE_INTEGER);
			responseResult.setMessage("【通行证ID】为正整数！");
			
			return responseResult;
		} else if(StringUtils.isBlank(clientCode)) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_NOT_POSITIVE_INTEGER);
			responseResult.setMessage("【客户端编号】不可为空！");
			
			return responseResult;
		}
		
		if(null == multipartRequest || !multipartRequest.getFileNames().hasNext()){
			return null;
		}
		
		for (Iterator<?> fileIterator = multipartRequest.getFileNames(); fileIterator.hasNext();) {  
			String key = (String) fileIterator.next();  
			MultipartFile multipartFile = multipartRequest.getFile(key);  
			MaterialTo materialTo = new MaterialTo();
			materialTo.setPassportId(passportId);
			materialTo.setClientCode(clientCode);
			
			if(null == multipartFile || 0 == multipartFile.getSize()){
				continue;
			}
			
			String originalFileName = multipartFile.getOriginalFilename();
			String contentType = multipartFile.getContentType();
			String fileName = multipartFile.getName();
			long fileSize = multipartFile.getSize();
			
			LOGGER.info("originalFileName = "
					+ originalFileName + ", contentType = " + contentType
					+ ", fileName = " + fileName + ", fileSize = " + fileSize);

			if(500 > fileSize) {
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("图片大小不可小于 500 KB!");
				
				return responseResult;
			} else if(31457280 < fileSize) {
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("图片大小不可大于 30 MB!");
				
				return responseResult;
			}
			
			String expandedName = originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length());
			
			materialTo.setOriginalFileName(originalFileName);
			if(StringUtils.isNotBlank(expandedName)) {
				materialTo.setExpandedName(expandedName.substring(1, expandedName.length()));
			}
			materialTo.setFileSize(fileSize);
			
			String systemFileName = CommonUtils.UUIDGenerator() + expandedName;
			
			materialTo.setSystemFileName(systemFileName);
			
			String uploadPrefix = PropertiesUtils.getValue("material.image.original.path");
			String fileUploadPath = FolderUtils.getStoragePath(uploadPrefix, passportId);
			LOGGER.info("fileUploadPath = " + fileUploadPath);

			materialTo.setStoragePath(fileUploadPath + systemFileName);
			
			try {
				FileUploadUtil.saveFileFromInputStream(multipartFile.getInputStream(),
						fileUploadPath, systemFileName);
			} catch (Exception e) {
				e.printStackTrace();
			}  
			
			if(OperationSystemInfo.isLinux()) {
				ChmodShell.updateFolderAuth(materialTo.getStoragePath());
			}
			
			responseResult = this.materialService.saveMaterial(materialTo);
		}  
		
		return responseResult;
	}
	
	/**
	 * 批量删除【素材】
	 * @param ids 【IDs】
	 * @param passportId 通行证ID
	 * @return
	 */
	@RequestMapping( value = { "batchDeleteMaterial/{passportId}" }, method = { RequestMethod.POST } )
	public ResponseResult batchDeleteMaterial(String ids, @PathVariable int passportId) {
		LOGGER.info("ids = {}, passportId = {}", ids, passportId);
		
		ResponseResult responseResult = this.materialService.batchDeleteMaterialById(ids, passportId); 
		
		return responseResult;
	}
}
